import { createRouter, createWebHistory } from 'vue-router';
import LoginPage from '../pages/views/LoginPage.vue';
import RegisterPage from '../pages/views/RegisterPage.vue';
import ForgotPassword from '../pages/views/ForgotPassword.vue';
import Myhomepage from "../pages/myhome/Myhomepage.vue";
import adminPage from "@/pages/myhome/dRootPage/rootIndex.vue";
import userSetting from "@/pages/myhome/dRootPage/menu/userSetting.vue";
import SystemInfo from "@/pages/myhome/dRootPage/menu/SystemInfo.vue";
import productDetails from '../pages/views/ProductDetails.vue';

const routes = [
  {
    path: '/',
    name: 'root',
    component: Myhomepage // 根路径加载首页
  },
  {
    path: '/login',
    name: 'login',
    component: LoginPage
  },
  {
    path: '/index',
    name: 'myhomepage',
    component: Myhomepage
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterPage
  },
  {
    path: '/forgot-password',
    name: 'forgotpassword',
    component: ForgotPassword
  },
  {
    path: '/adminPage',
    name: 'adminPage',
    children: [
      {
        path: '/userSetting',
        name: 'userSetting',
        component: userSetting
      },
      {
        path: '/SystemInfo',
        name: 'SystemInfo',
        component: SystemInfo
      },
    ],
    component: adminPage
  },
  {
    path: '/ProductDetails/:id',
    name: 'ProductDetails',
    component: productDetails
  }
  // 你可以在这里继续添加其他页面的路由
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

  // 允许未登录用户访问根路径、登录页、注册页和忘记密码页
  if (
    (to.path === '/' || 
    to.path === '/login' || 
    to.path === '/register' || 
    to.path === '/forgot-password') ||
    isLoggedIn
  ) {
    next();
  } else {
    // 未登录时，尝试访问需要登录的路径会重定向到登录页
    next({ name: 'login' });
  }
});

export default router;
